package com.dpad.telematicsclientapp.loginmodule


import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.ScrollView
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.dpad.crmclientapp.android.widget.CommonButton
import com.dpad.telematicsclientapp.mvp.kit.Kits
import com.dpad.telematicsclientapp.netlibrary.Contances
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyActivity
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.CardItem3
import com.dpad.telematicsclientapp.presenter.LoginPresenter
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.utils.*
import kotlinx.android.synthetic.main.activity_kt_login.*
import rx.subscriptions.CompositeSubscription

@Route(path = Contances.URL_ACTIVITY_LOGIN, group =Contances.GROUP_LOGIN)
class KtLoginActivity : BaseCopyActivity<LoginPresenter>(), View.OnClickListener {


    //T激活让用户点击同意的弹出框
    lateinit var ppw: PopupWindow
    //弹出框界面
    lateinit var ppwView: View

    private lateinit var ll_content: LinearLayout
    private lateinit var tvCancle: TextView
    private lateinit var tvOk: TextView
    private lateinit var scview: ScrollView
    lateinit var inflater: LayoutInflater
    private var loginByPsw = true//账号密码登录

    private var needGoToMain = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
    }

    override fun initPageData() {
        StatusBarUtil.transparencyBar(this)
        //        }
        val userName = PreferenceUtils.getInstance(this).getString(Constant.LOGIN_NAME)
        MainApplicaton.setNeedShowPinDialog(false)
        needGoToMain = intent.getBooleanExtra(Constant.LOGIN_KEY, true)
        if (!Kits.Empty.check(userName)) {
            userNameTv.setText(userName)
            userNameTv.setSelection(userName.length)
        }
        /**
         * 获取验证码
         */
        verifyBt.setOnClickListener(this)
        /**
         * 忘记密码
         */
        forgetPwd.setOnClickListener(this)
        loginTypeTv.setOnClickListener(this)
        /**
         * 登录点击事件
         */
        pressLogin.click(object : CommonButton.ButtonPress {
            override fun click() {
                if (Kits.Empty.check(userNameTv.text.toString())) {
                    T.showToastSafeError("账号不能为空")
                    return
                }
                if (!RegUtil.checkMobile(userNameTv.text.toString())) {
                    T.showToastSafeError("手机号格式错误,请重新输入")
                    return
                }
                if (loginByPsw) {
                    if (Kits.Empty.check(passwordEdt.text.toString())) {
                        T.showToastSafeError("密码不能为空")
                        return
                    }
//                    if (!RegUtil.checkPassWord(passwordEdt.text.toString())) {
//                        T.showToastSafeError("密码格式错误" + getString(R.string.password_rule))
//                        return
//                    }
                    getP().startLogin(userNameTv.text.toString(), passwordEdt.text.toString(), loginByPsw)
                } else {
                    if (Kits.Empty.check(vCodeEdt.text.toString())) {
                        T.showToastSafeError("验证码不能为空")
                        return
                    }
                    if (!RegUtil.checkSmsCode(vCodeEdt.text.toString())) {
                        T.showToastSafeError("验证码输入错误")
                        return
                    }
                    getP().startLogin(userNameTv.text.toString(), vCodeEdt.text.toString(), loginByPsw)
                }

            }

        })

        showPswIm.setOnClickListener(this)
        backIm.setOnClickListener(this)
        changeUiByLoginType(loginByPsw)
        initPop()

        userNameTv.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {//失去焦点
                if (!RegUtil.checkMobile(userNameTv.text.toString())) {
                    underLineView.setErrorMsg("")
                } else {
                    underLineView.setErrorMsgInvisible()
                }

            } else {
                parentScr.scrollTo(0, 2000)
                underLineView.setErrorMsgInvisible()
            }
        }
        passwordEdt.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                parentScr.scrollTo(0, 3000)
            }

        }
        vCodeEdt.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                parentScr.scrollTo(0, 3000)
            }

        }
    }

    override fun getLayout(): Int {
        return R.layout.activity_kt_login
    }

    override fun newPresenter(subscriptions: CompositeSubscription?): LoginPresenter {
        return LoginPresenter()
    }

//    override fun getPageTitle(): String {
//        return "登录"
//    }

    override fun getNeedSetDarkStatusText(): Boolean {
        return false
    }

    fun showListViewData(result: List<CardItem3.ResultBean?>?) {
        if (result != null) {
            if (!result.isEmpty()) { //当T车列表长度大于0的时候，则证明有T车，且所有车辆未激活，此时跳转到T激活首页
//                val intent2 = Intent(this, TChooseCarActivity3::class.java)
//                intent2.putExtra("type", "0")
//                startActivity(intent2)

                //跳转到我的爱车列表
                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_TChooseCar, Contances.GROUP_MYCAR)
                        .withString("type","0")
                        .navigation(this@KtLoginActivity)


            } else {
                T.showToastSafeError("暂未查到您的合同信息")
            }
        } else {
            T.showToastSafeError("暂未查到您的合同信息")
        }
    }

//    fun showPPWsm(bean: Tsm.ResultBean?) {
//        if (bean != null) {
//            ll_content.removeAllViews()
//            scview.removeAllViews()
//            if (!(bean.serviceDetails == null || bean.serviceDetails == "")) {
//                val view1 = UIUtils.inflate(R.layout.item_dzwl_sm_addview)
//                val tv_content: AlignTextView = view1.findViewById(R.id.tv_content)
//                tv_content.text = bean.serviceDetails
//                ll_content.addView(view1)
//                scview.addView(ll_content)
//            } else {
//            }
//        } else {
//            T.showToastSafeError("获取使用规则失败")
//        }
//        backgroundAlpha(0.3f, this)
//        ppw.showAtLocation(tvCancle, Gravity.CENTER, 0, 100)
//    }

    fun gotoTcar() {
        if (MainApplicaton.isTcar) { //如果有激活的T车，则跳转到首页
            goToHomeActivity(true)
        } else { //如果没有已激活的T车，此时请求T车列表
            getP().getTcarList() //请求T车列表的接口，判断list长度，如果是大于0，则证明有T车未激活，如果等于0，则证明没有T车
        }
        backgroundAlpha(1f, this)
        ppw.dismiss()
        MainApplicaton.LOGINRESULTVO.isAgree = "1" //设置成已经点击过同意的状态
    }

    //设置的蒙板，弹窗的时候变成灰色
    fun backgroundAlpha(bgAlpha: Float, context: Activity) {
        val lp = context.window.attributes
        lp.alpha = bgAlpha //0.0-1.0
        context.window.attributes = lp
    }

    private fun initPop() {
        //车辆网页面提示弹窗
        //实例化inflater
        //车辆网页面提示弹窗
//实例化inflater
        inflater = LayoutInflater.from(this)
        //实例化ppwView
        ppwView = inflater.inflate(R.layout.dialog_t_jihuo, null)
        ppw = PopupWindow(ppwView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true)
        ppw.isFocusable = false //设置当前的PopupWindow是否获取焦点：true-获取焦点
        ppw.isOutsideTouchable = false //设置点击当前的popupWindow区域外的touch事件是否有效；
        ll_content = ppwView.findViewById(R.id.ll_content)
        tvCancle = ppwView.findViewById(R.id.tv_cancle)
        tvOk = ppwView.findViewById(R.id.tv_ok)
        scview = ppwView.findViewById(R.id.scview)
        //取消
        tvCancle.setOnClickListener {
            backgroundAlpha(1f, this@KtLoginActivity)
            ppw.dismiss()
        }
        //同意
        tvOk.setOnClickListener { getP().aggreeTips() }

    }

    /**
     * 登录成功
     */
    private fun loginSuggess() {
//        if (needGoToMain) {
        goToHomeActivity(true)
//        }
//        finish()
    }

    /**
     * 登录成功后处理
     */
    fun dealLogin( ) {
//        if (Kits.Empty.check(value.isAgree)) {//未同意协议
//            getP().showTips()
//        } else {
        if (MainApplicaton.userVehType == "0" || MainApplicaton.userVehType == "4") {//游客或者非t车 直接跳转
            loginSuggess()
        } else {
            if (MainApplicaton.isTcar) {//有t车
                loginSuggess()
            } else {//t车未激活,跳转到激活页面
                getP().selectjihuo()
            }
        }
//        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.backIm -> {
                goToHomeActivity(false)
            }
            R.id.showPswIm -> {
                if (passwordEdt.inputType == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    passwordEdt.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                    showPswIm.setImageResource(R.mipmap.login_close)
                } else {
                    passwordEdt.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                    showPswIm.setImageResource(R.mipmap.login_open)
                }
                val s: String = passwordEdt.text.toString()
                if (!Kits.Empty.check(s)) {
                    passwordEdt.setSelection(s.length)
                }
            }
            R.id.forgetPwd -> {
//                startActivity(Intent(this, ForgetPswActivity::class.java))

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_FORGET, Contances.GROUP_OTHER)
                        .navigation(this@KtLoginActivity)

            }
            R.id.verifyBt -> {
                verifyBt.requestSendVerifyNumber()
                getP().getVcoe(userNameTv.text.toString())

            }
            R.id.loginTypeTv -> {
                loginByPsw = !loginByPsw
                changeUiByLoginType(loginByPsw)
            }
        }
    }

    private fun changeUiByLoginType(flag: Boolean) {
        if (flag) {
            pswLl.visibility = View.VISIBLE
            vCodeLl.visibility = View.GONE
            loginTypeTv.text = "手机快捷登录"
            psNameTv.text = "密码"
        } else {
            pswLl.visibility = View.GONE
            vCodeLl.visibility = View.VISIBLE
            loginTypeTv.text = "账号登录"
            psNameTv.text = "验证码"
        }
        passwordEdt.setText("")
        vCodeEdt.setText("")

    }

    fun getVcodeError() {
        verifyBt.removeRunable()
        verifyBt.resetCounter()
    }

    override fun onBackPressed() {
        goToHomeActivity(false)
    }

    override fun onResume() {
        super.onResume()
        MainApplicaton.setNeedShowPinDialog(false)
    }


    private fun goToHomeActivity(isLoginSuccess: Boolean) {
//        val intent = Intent(this, HomeActivity::class.java)
//        intent.putExtra("loginStatus", isLoginSuccess)
//        startActivity(intent)
//        finish()

        ARouter.getInstance()
                .build(Contances.URL_ACTIVITY_HOME, Contances.GROUP_HOME)
                .withBoolean("loginStatus",isLoginSuccess)
                .navigation(this@KtLoginActivity)

        finish()


    }


    override fun getPageTitle(): String {
        return TitleToCode.TYPE2.title
    }

    override fun isTActivity(): Boolean {
        return true
    }

}
